<?php
class Merchant_OrdersController extends Zend_Controller_Action
{
    public function preDispatch(){
		$this->tplDirectory = "merchant/orders/";
	}

	public function indexAction(){
        $lang=isset($_COOKIE['LANGUAGES'])?$_COOKIE['LANGUAGES']:'en';
        if($lang=='en'){
            $orderStatus = Merchant_Service_Orders::$orderStatus;
        }else{
            $orderStatus = Merchant_Service_Orders::$orderStatusCn;
        }
		$this->view->orderStatus = $orderStatus;
		$serviceObj = new Merchant_Service_Product();
		$loginInfo = $serviceObj->getLoginInfo();
		$customerId = $loginInfo->customer["customer_id"];
		$this->view->customerId = $customerId;
		$status = $this->_request->getParam('status','');

		if($status===''){
        	$status = 1;	//状态默认为草稿
        }
        $this->view->status = $status;

        if($this->_request->isPost()){
        	$orders_status = $this->_request->getParam('orders_status','');
        	if($orders_status===''){
        		$orders_status = 1;	//状态默认为草稿
        	}
            $page = $this->_request->getParam('page',1);
			$pageSize = $this->_request->getParam('pageSize');
            $orders_code_sch = $this->_request->getParam('orders_code_sch','');		//搜索表单提交的订单代码
            $customer_order_code = $this->_request->getParam('ReferenceNo','');		//	客户参考号
            $createDate = $this->_request->getParam('createDate','');		//	客户参考号
            $shipping_method = $this->_request->getParam('shipping_method','');		//	客户参考号
            $shipping_method = trim($shipping_method);
            $shipping_method = strtoupper($shipping_method);
            $underreview_status = $this->_request->getParam('underreview_status',0);		//	异常
            $underreview_status = $underreview_status?array(1,2,3):array(0);
            
            $page = $page?$page:1;
            // $orders_status = $orders_code_sch?'':$orders_status;
            $condition=array(
				'customer_id'=>$customerId,
				'orders_status'=>$orders_status,
				'shipping_method'=>$shipping_method,
			);
            
            
			$orders_code_sch && $condition['orders_code'] = trim($orders_code_sch);
			$customer_order_code && $condition['customer_order_code'] = trim($customer_order_code);
			$createDate && $condition['add_date'] = $createDate;
//			print_r($condition);exit;
           
			//各状态的符合条件的订单数量
			$tempCondition = $condition;
			//delete状态
			$tempCondition['orders_status'] = 0;
//			$tempCondition['underreview_status'] = array(0);
			$deleteTotal = Merchant_Service_Orders::getByCondition($tempCondition,'count(*)','',0,0);
			//draft状态
			$tempCondition['orders_status'] = 1;
//			$tempCondition['underreview_status'] = array(0);
			$draftTotal = Merchant_Service_Orders::getByCondition($tempCondition,'count(*)','',0,0);
			//confirm状态
			$tempCondition['orders_status'] = 2;
//			$tempCondition['underreview_status'] = array(0);
			$confirmTotal = Merchant_Service_Orders::getByCondition($tempCondition,'count(*)','',0,0);
			//insufficient状态
			$tempCondition['orders_status'] = 4;
//			$tempCondition['underreview_status'] = array(1,2);
			$insufficientTotal = Merchant_Service_Orders::getByCondition($tempCondition,'count(*)','',0,0);
			//proccesing状态
			$tempCondition['orders_status'] = 3;
			if($tempCondition['orders_status']==3){
				$tempCondition['underreview_status'] = array(0,1,2,3);
// 				$condition['underreview_status']=array(0,1,2,3);
				$proccesingTotal = Merchant_Service_Orders::getByCondition($tempCondition,'count(*)','',0,0);
				unset($tempCondition['underreview_status']);
			}
           
			//shipped状态
			$tempCondition['orders_status'] = 5;
//			$tempCondition['underreview_status'] = array(0);
			$shippedTotal = Merchant_Service_Orders::getByCondition($tempCondition,'count(*)','',0,0);
			//delivered状态
			$tempCondition['orders_status'] = 6;
//			$tempCondition['underreview_status'] = array(0);
			$deliveredTotal = Merchant_Service_Orders::getByCondition($tempCondition,'count(*)','',0,0);
            
			$total = Merchant_Service_Orders::getByCondition($condition,'count(*)','',0,0);
			
			
			$data=array('ask'=>0);
            if($total>0){
				$rows = Merchant_Service_Orders::getByCondition($condition,'*','add_time desc',$page,$pageSize);
                if (!empty($rows)) {
                    foreach ($rows as $key => $val) {
                        if (($val['orders_status'] == '5' && $val['process_status'] == '5') || $val['orders_status'] == '6') {
                            $ordershipRow = Merchant_Service_OrderShip::getByValue($val['orders_code'], 'orders_code');
                            if (!empty($ordershipRow)) {
                                $rows[$key]['tracking_number'] = $ordershipRow['tracking_number'];
                            } else {
                                $rows[$key]['tracking_number'] = '';
                            }
                        }
                    }
                }
				$data=array(
					'total'=>$total,
					'result'=>$rows,
					'ask'=>1,
				);
            }
			$data['statusTotal'] = array(
							"deleteTotal" => $deleteTotal,
							"draftTotal" => $draftTotal,
							"confirmTotal" => $confirmTotal,
							"insufficientTotal" => $insufficientTotal,
							"proccesingTotal" => $proccesingTotal,
							"shippedTotal" => $shippedTotal,
							"deliveredTotal" => $deliveredTotal,
						);
            die(Zend_Json::encode($data));
        }else{
        	$shipType = Merchant_Service_ShipType::getAll();
        	$shipTypeArr = array();
        	foreach($shipType as $v){
        		$shipTypeArr[$v['st_code']] = $v;
        	}
        	ksort($shipTypeArr);
//         	print_r($shipTypeArr);exit;
        	$this->view->shipType = $shipTypeArr;
            echo Cff::renderTpl($this->tplDirectory."index.tpl","user-layout");
        }
    }

    public function getOperationAction(){
        $lang=isset($_COOKIE['LANGUAGES'])?$_COOKIE['LANGUAGES']:'en';
        if($lang=='en'){
    	    $rows = Merchant_Service_Orders::$operationArr;
        }else{
            $rows = Merchant_Service_Orders::$operationArrCn;
        }
    	$status = $this->_request->getParam('status','');
    	$data=array('ask'=>0);
    	if($status || $status ==='0'){
    		$res = $rows[$status];
    		$data=array(
				'result'=>$res,
				'ask'=>1
			);
    	}

		die(Zend_Json::encode($data));
    }

    public function editStatusAction(){
    	$orderids = $this->_request->getParam('orderids','');
    	$orders_status = $this->_request->getParam('batchStatus','');
		$CheckPlan = $this->_request->getParam("unCheckPlan",false);
		$feeEnforce = $this->_request->getParam("enforce",0);
		$feeEnforce = false;
		$CheckPlan=false;
    	$check =array();
    	if(!is_array($orderids)){
    		$orderids = array($orderids);
    	}
    	foreach ($orderids as $key => $val){
    		$check[] = Merchant_Service_Orders::changeStatus($val,$orders_status,$CheckPlan,!empty($feeEnforce));
    	}
		$return = array(
			"ask" => true,
			"result" => $check
		);
		die(json_encode($return));
    }
    
    public function stopAction(){
    	$orderCode = $this->_request->getParam('orderids','');

    	$result=Merchant_Service_Orders::stop($orderCode[0]);
    	
    	if($result['ask']=='Error'){
    		$return = array(
    				"ask" => 0,
    				"result" => $result['message']
    		);
    		die(json_encode($return));
    	}
    	else{
    		$return = array(
    				"ask" => 1,
    				"result" => $result['message']
    		);
    		die(json_encode($return));
    	}
    	
    }


    public function infoAction(){
        $sp_id = $this->_request->getParam('sp_id',0);
        try{
            $shipPrice = Shipping_Service_ShipPrice::getByValue($sp_id);
            $return = array(
                'ask' =>true,
                'list' =>$shipPrice
            );
        }catch(Exception $e){
            $return = array(
                'ask' =>false,
                'list' =>null
            );
        }
        echo Zend_Json::encode($return);
        exit;
    }

	public function editAction(){		  
		 
		if($this->_request->isPost()){
			  $obj = $this->_request;
			  $cn_description =$obj->getParam('cn_description',null);
			  $hs_code =$obj->getParam('hs_code',null);
			  $op_origin =$obj->getParam('op_origin',null);
			  $op_quantity =$obj->getParam('op_quantity',null);
			  $product_sku =$obj->getParam('product_sku',null);
			  $op_description =$obj->getParam('op_description',null);
			  $product_id =$obj->getParam('product_id',null);
			  $op_id =$obj->getParam('op_id',array());
  
			  $consignee_address1 =$obj->getParam('consignee_address1','');
			  $consignee_address2 =$obj->getParam('consignee_address2','');
			  $consignee_city =$obj->getParam('consignee_city','');
			  $consignee_company =$obj->getParam('consignee_company','');
			  $consignee_country_id =$obj->getParam('consignee_country_id','');
			  $consignee_email =$obj->getParam('consignee_email','');
			  $consignee_first_name =$obj->getParam('consignee_first_name','');
			  $consignee_last_name =$obj->getParam('consignee_last_name','');
			  $consignee_phone =$obj->getParam('consignee_phone','');
			  $consignee_region =$obj->getParam('consignee_region','');
			  $consignee_zip =$obj->getParam('consignee_zip','');
			  $customer_order_code =$obj->getParam('customer_order_code','');	//客户参考号ReferenceNo
			  $parcel_contents =$obj->getParam('parcel_contents','');
			  $parcel_declared_value =$obj->getParam('parcel_declared_value','0');			
			  $order_type =$obj->getParam('order_type','0');//订单类型
			  $parcel_declared_value = 0;
			  
			  $parcel_quantity =$obj->getParam('parcel_quantity','');
			  $remark =$obj->getParam('remark','');
			  $shipping_method =$obj->getParam('shipping_method','');
			  $order_id =$obj->getParam('order_id',0);
			  $shipping_fee_estimate =$obj->getParam('shipping_fee_estimate');
  
			  $serviceObj = Merchant_Service_Product::getInstance();
			  $loginInfo = $serviceObj->getLoginInfo();
			  $customer_id = $loginInfo->customer["customer_id"];
  
  
			  $order_product = array();
			  if(is_array($product_sku)){
				  foreach($product_sku as $i=>$val){
					 $productObj = new Merchant_Service_Product();
					 $product = $productObj->getProductInfo($product_id[$i]);
  //				   print_r($product);
					 $order_product[] =array(
						 'op_id' => $op_id[$i],
						 'product_id' => $product_id[$i],
						 'cn_description' => $product['category']['poc_value_cn'],
						 'hs_code' => $product['category']['poc_id'],
						 'op_category' => $product['category']['poc_id'],
						 //'op_origin' => $op_origin[$i],
						 'op_quantity' => $op_quantity[$i],
						 'product_sku' => $product_sku[$i],
						 'op_description' => $op_description[$i],
						 'op_unit_price' => $product['product_declared_value'],
						 'op_subtotal' => round($product['product_declared_value']*$op_quantity[$i],2),
						 'op_declared_value' => round($product['product_declared_value']*$op_quantity[$i],2),
						 'op_weight' => round($product['product_weight']*$op_quantity[$i],2),
					 );
					
					 $parcel_declared_value+= $product['product_declared_value']* $op_quantity[$i];
				  }
			  }
  
// 			  switch(count($order_product)){
// 				  case 1:
// 					  if($order_product[0]['op_quantity']==1){//一票一件
// 						  $orders_print_type = 0;
// 					  }elseif($order_product[0]['op_quantity']>1){//一票多见
// 						  $orders_print_type = 1;
// 					  }
// 					  break;
// 				  default :
// 					  $orders_print_type = 2;//多票多件
// 			  }
			  
			  if($order_type=='1'){
				$shipping_method='SELFPICKUP';//自提 运输方式
			  }
			  
			  $orderInfo =array(
				  'order_id' =>$order_id,
				  'customer_id' =>$customer_id,
				  'consignee_address1' => $consignee_address1,
				  'consignee_address2' =>$consignee_address2,
				  'consignee_city' =>$consignee_city,
				  'consignee_company' =>$consignee_company,
				  'consignee_country_id' =>$consignee_country_id,
				  'consignee_email' =>$consignee_email,
				  'consignee_first_name' =>$consignee_first_name,
				  'consignee_last_name' =>$consignee_last_name,
				  'consignee_phone' =>$consignee_phone,
				  'consignee_region' =>$consignee_region,
				  'consignee_zip' => $consignee_zip,
				  'customer_order_code' => $customer_order_code,
				  'parcel_contents' => $parcel_contents,
				  'parcel_declared_value' => $parcel_declared_value,
				  'parcel_quantity' => $parcel_quantity,
				  'remark' => $remark,
				  'shipping_method' => $shipping_method,
				  'order_product' =>$order_product,
				  'shipping_fee_estimate' =>$shipping_fee_estimate,
// 				  'orders_print_type'=>$orders_print_type
			  );
			  //去除前后空格
			  foreach($orderInfo as $k=>$v){
				  	if(!is_array($v)){
				  	  $orderInfo[$k] = trim($v);			  		
				  	}
			  }
			  

  //			print_r($orderInfo);exit;
			  $return = Merchant_Service_OrderProccess::addOrder($orderInfo);
			  if(isset($orderInfo['order_id']) && $orderInfo['order_id']>0) {
				  $return['act'] ='edit';
			  }
			  echo Zend_Json::encode($return);
			  exit ;
		  }else{
			  $orderId = $this->_request->getParam("orderId",0);
			  if($orderId > 0){//修改订单
				  $order = Merchant_Service_Orders::getByCondition(array("orderId" => $orderId));
				  if(is_array($order[0])){
					  $this->view->order = $order[0];
				  }
			  }
			  $warehouseList = Default_Service_Warehouse::getByCondition();
			  $countryList  = Default_Service_Country::getByCondition(null,'*','sort DESC');
			  $this->view->warehouseList  = $warehouseList;
			  $this->view->countryList  = $countryList;
			  echo Cff::renderTpl($this->tplDirectory."edit.tpl","user-layout");
		  }
	  }

    public function viewAction(){
    	  	
    	//$orders_code=$this->_request->getParam('orders_code');
    	$orderId = $this->_request->getParam("orderId",0);

    	if(!empty($orderId)){
    		$rows=Merchant_Service_Orders::getByValue($orderId,'order_id');
            if(!empty($rows)){
                if($rows['orders_status']=='5' && $rows['process_status']=='5' ){
                    $ordershipRow=Merchant_Service_OrderShip::getByValue($rows['orders_code'],'orders_code');
                    if(!empty($ordershipRow)){
                        $rows['tracking_number']=$ordershipRow['tracking_number'];
						$rows['ref_tracking_number']=$ordershipRow['ref_tracking_number'];
                    }
                }
                $rows['orders_status']=Merchant_Service_Orders::$orderStatus[$rows['orders_status']];
                $proRow=Merchant_Service_OrderProduct::getByCondition(array('orders_code'=>$rows['orders_code']));//getByCondition(array('order_id'=>$orderId))
            }else{
                $rows['orders_code']=null;
            }
    		$this->view->order = $rows;
    		$this->view->orders_code=$rows['orders_code'];
    	}
    	
    	echo $this->view->render($this->tplDirectory."view.tpl");
    	
    }
    
    public function getOrderLogAction(){
		$orders_code = $this->_request->getParam("orders_code",0);
		$order=array();
		if($orders_code){//修改订单
			$order = Merchant_Service_Orders::getByCondition(array("orders_code" => $orders_code));
			if(is_array($order[0])){
				$this->view->order = $order[0];
			}
		}

		$page = $this->_request->getParam("page",0);
		$pageSize = $this->_request->getParam("pageSize",20);
		$orderlog=new Merchant_Model_OrderStatusHistory();
		
		$results = $orderlog->getByValue($orders_code,'orders_code',$pageSize,$page);
		$total=$orderlog->getByValueCount($orders_code,'orders_code');
		$order_status=Merchant_Service_Orders::$orderStatus;
		
		
		foreach ($results as  $k=>$val){
			if($val['osh_statu']){
				$results[$k]['osh_statu']=$order_status[$val['osh_statu']];
			}	
		}
		

		if($results){
			$return['ask'] = true;
			$return['results'] = $results;
			$return['total'] = $total;
		}else{
			$return['ask'] = false;
		}
		
		die(json_encode($return));
	}
	
	
	public function getProductInfoAction(){
		$orders_code = $this->_request->getParam("orders_code",0);
		$page = $this->_request->getParam("page",0);
		$pageSize = $this->_request->getParam("pageSize",20);
		
		//$orderId = $this->_request->getParam("orderId",0);
		
		if(!empty($orders_code)){
			$rows=Merchant_Service_Orders::getByValue($orders_code,'orders_code');
			$rows['orders_status']=Merchant_Service_Orders::$orderStatus[$rows['orders_status']];
			$proRow=Merchant_Service_OrderProduct::getByCondition(array('orders_code'=>$rows['orders_code']));//getByCondition(array('order_id'=>$orderId))
			//     		print_r($proRow);exit;
			$subtotal=0;//订单总金额
			if(!empty($proRow)){
				foreach($proRow as $key => $value){
					$product=Merchant_Service_Product::getByProductId($value['product_id']);//getByProductId($value['product_id']);
					$proRow[$key]['product_title']=$product['product_title'];
		
					$Picture=Merchant_Service_ProductAttached::getProductPicture($value['product_id']);//获取图片
					if($Picture){
						$proRow[$key]['product_img']='/merchant/product/view-image/fileName/'.$Picture[0]['pa_path'].'/productId/'.$value['product_id'];
					}
					if(!$Picture){
						$Picture=Merchant_Service_ProductAttached::getLinksByProductId($value['product_id']);//获取图片

						if(isset($Picture[0]['pa_path'])){
							$proRow[$key]['product_img']=$Picture[0]['pa_path'];
						}
						
					}
					if(empty($Picture[0]['pa_path'])){
						//默认图片
						$proRow[$key]['product_img']="/images/disimage.php.jpg";
					}
					$proRow[$key]['subtotal']=$value['op_quantity']*$value['op_unit_price'];//产品总价
					$subtotal+=$proRow[$key]['subtotal'];
				}
			}
		
// 			$this->view->order = $rows;
// 			$this->view->orders_code=$rows['orders_code'];
// 			$this->view->productlist=$proRow;
// 			$this->view->subtotal=$subtotal;
		
		}
		
	
        if(!empty($proRow)){
			$return['ask'] = true;
			$return['results'] = $proRow;
			$return['total'] = count($proRow);
		}else{
			$return['ask'] = false;
		}
	
		die(json_encode($return));
	}
	

    public function deleteAction(){
        $return = array();
        $sp_id = $this->_request->getParam('sp_id',0);
        if(Shipping_Service_ShipPrice::delete($sp_id)){
            $return['ask'] =true;
            $return['list']['message'] = "Successful";
        }else{
            $return['ask'] =false;
            $return['list']['error'][] = "Fail.";
        }
        echo Zend_Json::encode($return);
        exit;
   }


   public function getShippingAction(){
        $return = array();
        $warehouse_id = $this->_request->getParam('warehouse_id',0);
        $country_id = $this->_request->getParam('country_id',0);

        $array = array(
            'warehouseId' => $warehouse_id,
            'countryId' => $country_id,
        );
        $shipFeeCalcObj = new Default_Service_ShipFeeCalc($array);
        $list= $shipFeeCalcObj->getAviableType();
        if(is_array($list)){
			foreach($list as $key => $val){
				$newlist[$key]['st_code']=$val['st_code'];
				$newlist[$key]['st_name_cn']=$val['st_name_cn'];
				$newlist[$key]['st_name']=$val['st_name'];
			}
            $return['ask'] =true;
            $return['list'] = $newlist;
        }else{
            $return['ask'] = false;
            $return['list']['error'][] = "Failure.";
        }
        echo Zend_Json::encode($return);
		unset($list);
        exit;
   }

   public function getCostAction(){
        $return = array();
        $warehouse_id = $this->_request->getParam('warehouse_id',0);
        $country_id = $this->_request->getParam('country_id',0);
        $weight = $this->_request->getParam('weight',0);
        $shipping_method = $this->_request->getParam('shipping_method','');
        $product_skus = $this->_request->getParam('product_sku','');		
		$product_skus = trim($product_skus,",");
		$product_skus = explode(",",$product_skus);
		
		
		$model_product = new Merchant_Model_Product();	
		
        $serviceObj = Merchant_Service_Product::getInstance();
        $loginInfo = $serviceObj->getLoginInfo();
        $customerId = $loginInfo->customer["customer_id"];

		$products = $model_product->getProductBySkus($product_skus,$customerId);
		
		$extra_weight = 0;
		if($products){//第所有产品中产品包材重量最重
			$product_ids = array();
			foreach($products as $v){
				$product_ids[] = $v['product_id'];
			}
			$extra_weight = $model_product->getProductPackageWeightByProductId($product_ids);	
			
		}
			
        $shipType = Default_Service_ShipType::getByValue($shipping_method,'st_code');
        $array = array(
            'warehouseId'=>$warehouse_id,
            'countryId'=>$country_id,
            'stId'=> @$shipType['st_id'],
            'weight'=> ($weight+$extra_weight),
            'length'=> 0,
            'width'=> 0,
            'height'=> 0,
            'customerId'=>$customerId,
        );
        $obj =new Default_Service_ShipFeeCalc($array);
        $fee = $obj->calcFeeByType();
        if(is_array($fee)){
			$currency = Default_Service_Currency::changeCurrency("0.25","USD","RMB");	
        	if($currency){
        		$fee['inter_fee'] = $fee['inter_fee']+$currency['value'];//加上包材费用
        	}
            $return['ask'] =true;            
            $return['list'] = $fee;
        }else{
            $return['ask'] = false;
            $return['list']['error'][] = "No price.";
        }
        echo Zend_Json::encode($return);
        exit;
   }
   
   public function validateRefnoAction(){
		if(trim($this->_request->customer_order_code) != ''){
			$customerId = Merchant_Service_Customer::getCustomerId(null);
			$condition = array("customer_id" => $customerId,
								"customer_order_code" => $this->_request->customer_order_code,
								"order_id" => $this->_request->orderId,
								"order_status_arr_not" =>array(0)
								);
			$order = Merchant_Service_Orders::getByCondition($condition);

			if(count($order) > 0){
				die(json_encode(false));
			}
			die(json_encode(true));
		}
   }
   
	public function uploadProcessingAction(){	//订单上传处理
		$fileData = array();
		$serviceObj = new Merchant_Service_Orders();		
		$fileName = $_FILES['orderFile']['name'];
		$filePath = $_FILES['orderFile']['tmp_name'];
		
		$fileData = $serviceObj->readUploadFile($fileName,$filePath);
		$fileData['ask'] = 0;
		if (isset($fileData['data']) && $fileData['data']){			
			$fileData['ask'] = 1;
		}

		die(Zend_Json::encode($fileData));
		
	}
	
	/**
	 *  检查批量上传的数据
	 * 
	 */
	public function uploadCheckDataAction(){
		$fileData = $this->_request->getParam('orderJson','');
		
		$serviceObj = new Merchant_Service_Orders();
		$fileData['ask'] = 0;
		if (isset($fileData['data']) && $fileData['data']){
			$fileData['data'] = $serviceObj->uploadDataValidator($fileData['data']);
			$fileData['ask'] = 1;
		}
		
		die(Zend_Json::encode($fileData));
	}
	
	/**
	 * 处理批量上传时的 产品添加
	 * 
	 */
	public function productBatchAddAction(){
		$fileData = $this->_request->getParam('orderJson','');
		$fileData['ask'] = 0;
		$lineKey = $this->_request->getParam('lineKey','');
		$productInfo = array('product_sku'=>$this->_request->getParam('product_sku',''),
					'product_title'=>$this->_request->getParam('product_title',''),
					'category'=>$this->_request->getParam('category',''),
					'op_quantity'=>$this->_request->getParam('op_quantity',1),
					'op_description'=>$this->_request->getParam('op_description',''),
					'product_id'=>$this->_request->getParam('product_id',''),
					'op_declared_value'=>$this->_request->getParam('op_declared_value',''),
					'op_unit_price'=>$this->_request->getParam('op_unit_price',''),
					'op_weight'=>$this->_request->getParam('op_weight','')
		);
		foreach ($fileData['data'] as $key => $val){
			if($lineKey == $key){
				$fileData['data'][$key]['order_product'][] = $productInfo; 
				$fileData['ask'] = 1;
			}
		}

		die(Zend_Json::encode($fileData));		
	}
		
	/**
	 * excel 批量上传的数据写入数据库
	 *
	 */
	public function excelUploadAddAction(){
		$warehouse_id = 1;	//目前 只有一个仓库，id 默认为 1 
		$fileData = $this->_request->getParam('orderJson','');		
		$serviceObj = new Merchant_Service_Orders();
		if (isset($fileData['data']) && $fileData['data']){			
			$orderArr = $fileData['data'];			
		}
		
		if(is_array($orderArr) && $orderArr){
			foreach ($orderArr as $key => $val){
				$product_skus = array();
				$allweight = 0;
				foreach ($val['order_product'] as $key2 => $val2){
					$product_skus[] = $val2['product_sku'];
					$allweight += $val2['op_quantity']*$val2['op_weight'];					
				}
				
				$country_id = $val['consignee_country_id'];
				$shipping_method = $val['shipping_method'];
				$estimateFee = Merchant_Service_OrderProccess::getEstimateFee($warehouse_id,$country_id,$shipping_method,$allweight,$product_skus);	
				if(is_array($estimateFee) && $estimateFee){
					$return['list']['message'] = $val['customer_order_code'].' '.$shipping_method.' Fail.100';
					$data[] = $return;
				}else {
					$val['shipping_fee_estimate'] = $estimateFee;
					if(is_array($val) && $val){
						$return = Merchant_Service_OrderProccess::addOrder($val);				
						$data[] = $return;	
					}
				}
				
			}
			
		}else {
			$data[] =array('ask'=>0,'list'=>array('error'=>array('Fail.101')));
		}

		die(Zend_Json::encode($data));
	}
	
	public function getShipMethodAction(){
		$allMethod = Merchant_Service_ShipType::getAll();
		$shipMethodArr = $data = array();
		$data['ask'] = 0;
		foreach ($allMethod as $key => $val){
			$shipMethodArr[] = $val['st_code'];
		}
		if($shipMethodArr){
			$data['ask'] = 1;
			$data['data'] = $shipMethodArr;
		}		
		die(Zend_Json::encode($data));
		
	}
	
	public function getCountriesAction(){
		$allCountries = Default_Service_Country::getAll();
		
		$countriesArr = $data = array();
		$data['ask'] = 0;
		foreach ($allCountries as $key => $val){
			$countriesArr[$key]['country_id'] = $val['country_id'];
			$countriesArr[$key]['en_name'] = $val['en_name'];
			$countriesArr[$key]['country_code'] = $val['country_code'];
		}
		if($countriesArr){
			$data['ask'] = 1;
			$data['data'] = $countriesArr;
		}
		die(Zend_Json::encode($data));
		
	}

    public function getTrackInfoAction(){
        $trackingNo = $this->_request->getParam("tracking_number",0);
   		$data['ask'] = 0;
        $data['msg']='';
        $data['result']=array();
   		die(Zend_Json::encode($data));

   	}

    public function getOrderShipAction(){
        $orders_code = $this->_request->getParam("orders_code",0);
   		$data['ask'] = 0;
        $data['msg']='';
        $data['result']=array();
        try{
            $ordershipRow = Merchant_Service_OrderShip::getByValue($orders_code,'orders_code');
            if (!empty($ordershipRow)) {
                $data['ask'] = 1;
                $data['result'][]=$ordershipRow;
                unset($data['result']['os_shipping_fee_estimate']);
            }else{
                $data['msg']='No Result';
                die(Zend_Json::encode($data));
            }
        }catch(Zend_Exception $e){
            $data['msg']="error:{$e->getMessage()}";
        }
   		die(Zend_Json::encode($data));
   	}

   	public function editTestAction(){
   	    	
   	    if($this->_request->isPost()){
   	        $obj = $this->_request;
   	        $cn_description = $obj->getParam('cn_description', null);
   	        $hs_code = $obj->getParam('hs_code', null);
   	        $op_origin = $obj->getParam('op_origin', null);
   	
   	        $op_quantity = $obj->getParam('op_quantity', null);
   	        $product_sku = $obj->getParam('product_sku', null);
   	        $op_description = $obj->getParam('op_description', null);
   	        $product_id = $obj->getParam('product_id', null);
   	        $op_id = $obj->getParam('op_id', array());
   	
   	        $consignee_address1 = $obj->getParam('consignee_address1', '');
   	        $consignee_address2 = $obj->getParam('consignee_address2', '');
   	        $consignee_city = $obj->getParam('consignee_city', '');
   	        $consignee_company = $obj->getParam('consignee_company', '');
   	        $consignee_country_id = $obj->getParam('consignee_country_id', '');
   	        $consignee_email = $obj->getParam('consignee_email', '');
   	        $consignee_first_name = $obj->getParam('consignee_first_name', '');
   	        $consignee_last_name = $obj->getParam('consignee_last_name', '');
   	        $consignee_phone = $obj->getParam('consignee_phone', '');
   	        $consignee_region = $obj->getParam('consignee_region', '');
   	        $consignee_zip = $obj->getParam('consignee_zip', '');
   	        $customer_order_code = $obj->getParam('customer_order_code', ''); // 客户参考号ReferenceNo
   	        $parcel_contents = $obj->getParam('parcel_contents', '');
   	        $parcel_declared_value = $obj->getParam('parcel_declared_value', '0');
   	        $order_type = $obj->getParam('order_type', '0'); // 订单类型
   	        $parcel_declared_value = 0;
   	
   	        $parcel_quantity = $obj->getParam('parcel_quantity', '');
   	        $remark = $obj->getParam('remark', '');
   	        $shipping_method = $obj->getParam('shipping_method', '');
   	        $order_id = $obj->getParam('order_id', 0);
   	        $shipping_fee_estimate = $obj->getParam('shipping_fee_estimate');
   	
   	        $serviceObj = Merchant_Service_Product::getInstance();
   	        $loginInfo = $serviceObj->getLoginInfo();
   	        $customer_id = $loginInfo->customer["customer_id"];
   	
   	        $productObj = new Merchant_Service_Product();
   	        $ps = $productObj->getList(array(), 1, 100);
   	
   	        foreach ($ps as $p) {
   	            $op_quantity = $product_sku = $op_description = $product_id = array();
   	            $op_quantity[] = 1;
   	            $product_sku[] = $p['product_sku'];
   	            $op_description[] = $p['product_title'];
   	            $product_id[] = $p['product_id'];
   	
   	            $order_product = array();
   	            if (is_array($product_sku)) {
   	                foreach ($product_sku as $i => $val) {
   	                    $productObj = new Merchant_Service_Product();
   	                    $product = $productObj->getProductInfo($product_id[$i]);
   	                    // print_r($product);
   	                    $order_product[] = array(
   	                            'op_id' => $op_id[$i],
   	                            'product_id' => $product_id[$i],
   	                            'cn_description' => $product['category']['poc_value_cn'],
   	                            'hs_code' => $product['category']['poc_id'],
   	                            'op_category' => $product['category']['poc_id'],
   	                            // 'op_origin' => $op_origin[$i],
   	                            'op_quantity' => $op_quantity[$i],
   	                            'product_sku' => $product_sku[$i],
   	                            'op_description' => $op_description[$i],
   	                            'op_unit_price' => $product['product_declared_value'],
   	                            'op_subtotal' => round($product['product_declared_value'] * $op_quantity[$i], 2),
   	                            'op_declared_value' => round($product['product_declared_value'] * $op_quantity[$i], 2),
   	                            'op_weight' => round($product['product_weight'] * $op_quantity[$i], 2)
   	                    );
   	
   	                    $parcel_declared_value += $product['product_declared_value'] * $op_quantity[$i];
   	                }
   	            }
   	
   	            if ($order_type == '1') {
   	                $shipping_method = 'SELFPICKUP'; // 自提 运输方式
   	            }
   	
   	            $orderInfo = array(
   	                    'order_id' => $order_id,
   	                    'customer_id' => $customer_id,
   	                    'consignee_address1' => $consignee_address1,
   	                    'consignee_address2' => $consignee_address2,
   	                    'consignee_city' => $consignee_city,
   	                    'consignee_company' => $consignee_company,
   	                    'consignee_country_id' => $consignee_country_id,
   	                    'consignee_email' => $consignee_email,
   	                    'consignee_first_name' => $consignee_first_name,
   	                    'consignee_last_name' => $consignee_last_name,
   	                    'consignee_phone' => $consignee_phone,
   	                    'consignee_region' => $consignee_region,
   	                    'consignee_zip' => $consignee_zip,
   	                    'customer_order_code' => $customer_order_code,
   	                    'parcel_contents' => $parcel_contents,
   	                    'parcel_declared_value' => $parcel_declared_value,
   	                    'parcel_quantity' => $parcel_quantity,
   	                    'remark' => $remark,
   	                    'shipping_method' => $shipping_method,
   	                    'order_product' => $order_product,
   	                    'shipping_fee_estimate' => $shipping_fee_estimate,
   	            );
   	            // 去除前后空格
   	            foreach ($orderInfo as $k => $v) {
   	                if (! is_array($v)) {
   	                    $orderInfo[$k] = trim($v);
   	                }
   	            }
   	
   	            // print_r($orderInfo);exit;
   	            $return = Merchant_Service_OrderProccess::addOrder($orderInfo);
   	            if (isset($orderInfo['order_id']) && $orderInfo['order_id'] > 0) {
   	                $return['act'] = 'edit';
   	            }
   	        }
   	        echo Zend_Json::encode($return);
   	        exit();
   	    }else{
   	        $orderId = $this->_request->getParam("orderId",0);
   	        if($orderId > 0){//修改订单
   	            $order = Merchant_Service_Orders::getByCondition(array("orderId" => $orderId));
   	            if(is_array($order[0])){
   	                $this->view->order = $order[0];
   	            }
   	        }
   	        $warehouseList = Default_Service_Warehouse::getByCondition();
   	        $countryList  = Default_Service_Country::getByCondition(null,'*','sort DESC');
   	        $this->view->warehouseList  = $warehouseList;
   	        $this->view->countryList  = $countryList;
   	        echo Cff::renderTpl($this->tplDirectory."edit.tpl","user-layout");
   	    }
   	}
}